//
//  ChangeUserInfoController.m
//  FinancialProduct
//  联系方式及邮箱
//  Created by Stella on 2017/9/7.
//  Copyright © 2017年 maq. All rights reserved.
//

#import "Header.h"
#import "HandleNetProduct.h"
#import "SVProgressHUD.h"
#import "AddressCell.h"
#import "ValidateTools.h"
#import "UserModel.h"
#import "TKAlertCenter.h"
#import "ChangeUserInfoController.h"

@interface ChangeUserInfoController (){
    int provinceId;
    int cityId;
    
    NSString *countryName ;//城市
    NSString *provinceName ;//城市
    
    NSString *cityName ;//城市
    NSString *detailAddress ;//详细地址
    NSString *mobile;//固定电话
    NSString *email;//邮箱
    NSString *postcode ;//邮编
    
}
@property (weak, nonatomic) IBOutlet UIPickerView *myPickView;
@property (strong, nonatomic)NSMutableArray *allDataArray;
@property (strong, nonatomic)NSMutableArray *provinceNameArray;
@property (strong, nonatomic)NSMutableArray *cityNameArray;
@property (strong, nonatomic)NSArray *textArray;
@property (strong, nonatomic)NSMutableArray *textContentArray;
@end

@implementation ChangeUserInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"联系方式及邮箱";
    _allDataArray=[[NSMutableArray alloc] initWithCapacity:0];
    _provinceNameArray=[[NSMutableArray alloc] initWithCapacity:0];
    _cityNameArray=[[NSMutableArray alloc] initWithCapacity:0];
    _textContentArray=[[NSMutableArray alloc] initWithCapacity:0];
    cityId=0;
    provinceId=0;
    countryName=_userInfo[@"PreferredCountry"];
    provinceName=_userInfo[@"PreferredProvince"];
    cityName=_userInfo[@"PreferredCity"];
    detailAddress=_userInfo[@"PreferredAddress"];
    mobile=_userInfo[@"Mainlyphone"];
    email=_userInfo[@"PersonEmail"];
    postcode=_userInfo[@"PreferredZip1"];
    
    _textArray=@[@"请选择地区",@"请输入详细地址",@"请输入固定电话",@"请输入电子邮箱",@"请输入邮编"];
    NSString *cccc=[NSString stringWithFormat:@"%@-%@-%@",countryName,provinceName,cityName];
    NSArray *aaa=@[cccc,detailAddress,
                        mobile,email,
                        postcode];
    
    [_textContentArray addObjectsFromArray:aaa];
    [self sortMyCityData];
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 44)];
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    [rightBtn addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:rightBtn]];
}

-(void)save:(UIBarButtonItem *)barBt{
    /*
     *****UpdateMyInformation******
     *
     * PreferredCountry 国家
     * PreferredProvince
     * PreferredCity
     * PreferredZip 邮编
     * PreferredAddress 地址
     * MainlyphoneAreaCode 区号
     * Mainlyphone 电话
     * PersonEmail 邮箱
     * CustomerID 客户ID
     *****
     */
    if (countryName.length==0||provinceName.length==0||cityName.length==0) {
      
        [[TKAlertCenter defaultCenter]postAlertWithMessage:@"请选择城市"];
        return;
    }
    if (detailAddress.length==0) {
     
        [[TKAlertCenter defaultCenter]postAlertWithMessage:@"请输入详细地址"];
        return;
    }
//    if (mobile.length==0) {
//        [SVProgressHUD showInfoWithStatus:@"请输入固定电话"];
//        return;
//    }
//    if ( ![ValidateTools validateNumber:mobile]) {
//        [SVProgressHUD showInfoWithStatus:@"固定电话格式不正确"];
//        return;
//    }
//    if (email.length==0) {
//        [SVProgressHUD showInfoWithStatus:@"请输入邮箱"];
//        return;
//    }
//    if ( ![ValidateTools validateEmail:email]) {
//        [SVProgressHUD showInfoWithStatus:@"邮箱格式不正确"];
//        return;
//    }
    if (postcode.length==0) {
        [[TKAlertCenter defaultCenter]postAlertWithMessage:@"请输入邮编"];
        return;
    }
    UserModel *model=[UserModel getUser];
    int mid=[model.CustomerID intValue];
//    detailAddress=@"";
//    countryName=@"";
//    provinceName=@"";
//    cityName=@"";
    NSDictionary *params=@{@"AAAMethodName":@"UpdateMyInformation",
                           @"PreferredCountry":countryName,
                           @"PreferredProvince":provinceName,
                           @"PreferredCity":cityName,
                           @"PreferredZip":postcode,
                           @"PreferredAddress":detailAddress,
                           @"MainlyphoneAreaCode":@"0",
                           @"Mainlyphone":mobile,
                           @"PersonEmail":email,
                           @"CustomerID":@(mid)};
    [HandleNetProduct getListforParams:params Success:^(NSArray *data) {
        [[TKAlertCenter defaultCenter]postAlertWithMessage:@"修改成功"];
        [self.navigationController popViewControllerAnimated:YES];
    } Failure:^(NSString *errorInfo) {
        
    }];
}
- (IBAction)chooseCancel:(id)sender {
    self.chooseView.hidden=YES;
}
- (IBAction)chooseOK:(id)sender {
    self.chooseView.hidden=YES;
    provinceName=_provinceNameArray[provinceId];
    countryName=@"中国";
    cityName =_cityNameArray[provinceId][cityId];
    NSString *cccc=[NSString stringWithFormat:@"%@-%@-%@",countryName,provinceName,cityName];
    [_textContentArray replaceObjectAtIndex:0 withObject:cccc];
    [self.mTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
}
-(void)sortMyCityData{
    NSString *path=[[NSBundle mainBundle]pathForResource:@"Country_Province_City" ofType:@"json"];
    NSData *pathData=[NSData dataWithContentsOfFile:path];
    NSArray *allDataArray = [NSJSONSerialization JSONObjectWithData:pathData options:NSJSONReadingMutableLeaves error:nil];
    [_allDataArray addObjectsFromArray:allDataArray];
//    NSLog(@"cityAa==%@",allDataArray);
  
    //存储国家的名字
    NSMutableArray *countryName=[[NSMutableArray alloc] init];
    for (int i=0; i<allDataArray.count; i++) {
        //国家的字典
        NSDictionary *countryDic=allDataArray[i];
        [countryName addObject:countryDic[@"name"]];
        //所有省的字典
        NSArray *provinceDataArray=countryDic[@"child"];

        for (int j=0; j<provinceDataArray.count; j++) {
            //某个省的信息
            NSDictionary *provinceDic=provinceDataArray[j];
            [_provinceNameArray addObject:provinceDic[@"name"]];
            //省下的市
            NSArray *cityData=provinceDic[@"child"];
            NSMutableArray *cityNa=[NSMutableArray arrayWithCapacity:0];
            for (int k=0; k<cityData.count; k++) {
                [cityNa addObject:cityData[k][@"name"]];
            }
            [_cityNameArray addObject:cityNa];
        }
        
    }
//    NSLog(@"_provinceNameArray==%@",_provinceNameArray);
//    NSLog(@"_cityNameArray==%@",_cityNameArray);
    [self.myPickView reloadAllComponents];
    [self.myPickView selectRow:provinceId inComponent:1 animated:YES];
    [self.myPickView selectRow:cityId inComponent:1 animated:YES];
  
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
//UIPickerViewDataSource中定义的方法，该方法的返回值决定该控件包含的列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView
{
    return 3; // 返回2表明该控件只包含2列
}

//UIPickerViewDataSource中定义的方法，该方法的返回值决定该控件指定列包含多少个列表项
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    // 由于该控件只包含一列，因此无须理会列序号参数component
    // 该方法返回teams.count，表明teams包含多少个元素，该控件就包含多少行
    
    if (component == 0) {
        return 1;
    }
    else if (component==1){
        return _provinceNameArray.count;
    }else{
        return [_cityNameArray[provinceId] count];
    }
}


// UIPickerViewDelegate中定义的方法，该方法返回的NSString将作为UIPickerView
// 中指定列和列表项的标题文本
//- (NSString *)pickerView:(UIPickerView *)pickerView
//             titleForRow:(NSInteger)row forComponent:(NSInteger)component
//{
//    // 由于该控件只包含一列，因此无须理会列序号参数component
//    // 该方法根据row参数返回teams中的元素，row参数代表列表项的编号，
//    // 因此该方法表示第几个列表项，就使用teams中的第几个元素
//    
//    if (component == 0) {
////        return self.allDataArray[0][@"name"];
//        return @"中国";
//    }else if (component==1){
//        return _provinceNameArray[row];
//    }else{
//        return _cityNameArray[provinceId][row];
//    }
//  
//}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view{
    

    if (component == 0) {
        UIView *vc=[[UIView alloc] init];
        UILabel *nameLa=[[UILabel alloc] initWithFrame:CGRectMake(20, 0, Main_Screen_Width/3-20, 20)];
        nameLa.textAlignment=NSTextAlignmentCenter;
        nameLa.font=[UIFont systemFontOfSize:16];
        nameLa.adjustsFontSizeToFitWidth = YES;
        nameLa.text=@"中国";
        [vc addSubview:nameLa];
        return vc;
    }else if (component==1){
        UIView *vc=[[UIView alloc] init];
        UILabel *nameLa=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width/3, 20)];
        nameLa.textAlignment=NSTextAlignmentCenter;
        nameLa.font=[UIFont systemFontOfSize:16];
        nameLa.adjustsFontSizeToFitWidth = YES;
        nameLa.text=_provinceNameArray[row];
        [vc addSubview:nameLa];
        return vc;
    }else{
        UIView *vc=[[UIView alloc] init];
        UILabel *nameLa=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width/3-10, 20)];
        nameLa.textAlignment=NSTextAlignmentCenter;
        nameLa.font=[UIFont systemFontOfSize:16];
        nameLa.adjustsFontSizeToFitWidth = YES;
        nameLa.text=_cityNameArray[provinceId][row];
        [vc addSubview:nameLa];
        return vc;
    }
    
}
// 当用户选中UIPickerViewDataSource中指定列和列表项时激发该方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    if (component == 1) {
        provinceId=(int)row;
        cityId=0;
         [self.myPickView reloadComponent:2];
    }else if (component==2){
        cityId=(int)row;
    }

    [self.myPickView reloadAllComponents];
    NSString *province=_provinceNameArray[provinceId];
    
    NSString *city = _cityNameArray[provinceId][cityId];
    NSLog(@"%@、%@",province,city);

}


// UIPickerViewDelegate中定义的方法，该方法返回的NSString将作为
// UIPickerView中指定列的宽度
-(CGFloat)pickerView:(UIPickerView *)pickerView
   widthForComponent:(NSInteger)component
{
    float width=Main_Screen_Width/3;
    // 如果是第一列，宽度为90
//    if(component ==0) {
//        return width-60;
//    }
    return width-10; // 如果是其他列（只有第二列），宽度为210
}
#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
 
    return _textArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    AddressCell *cell=[tableView dequeueReusableCellWithIdentifier:@"AddressCell" forIndexPath:indexPath];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.accessoryType=UITableViewCellAccessoryNone;
    if (indexPath.row==0) {
        cell.chooseBt.hidden=NO;
    }else{
        cell.chooseBt.hidden=YES;
    }
    if (indexPath.row == 2||indexPath.row == 4){//电话
        cell.mTextField.keyboardType = UIKeyboardTypeNumberPad;
    }else if (indexPath.row == 3){//电话
        cell.mTextField.keyboardType = UIKeyboardTypeEmailAddress;
    }else{
        cell.mTextField.keyboardType = UIKeyboardTypeDefault;
        
    }
    cell.mTextField.tag=indexPath.row;
    cell.mTextField.placeholder=self.textArray[indexPath.row];
    cell.mTextField.text=_textContentArray[indexPath.row];
    cell.chooseReturn = ^{
        self.chooseView.hidden=NO;
    };
    cell.returnTextBlock = ^(NSString *textContent) {
//        NSLog(@"indexPath.row ===%ld  textContent=%@",indexPath.row,textContent );
        switch (indexPath.row) {
            case 0:
            case 1:
                detailAddress=textContent;
                break;
            case 2:
                mobile=textContent;
                break;
            case 3:
                email=textContent;
                break;
            case 4:
                postcode=textContent;
                break;
            default:
                break;
        }
    };
    
    return cell;

    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10.0;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}


@end
